package com.tuzhi.gateway.config;

import com.tuzhi.gateway.filter.LoginTokenFilter;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * 功能说明：
 *
 * @author abu
 * @version 1.1.0
 * @date 2023/3/14
 */
@Configuration
@Data
public class GatewayConfig {

    @Value("${client.source}")
    private String source;

    @Bean
    public RouteLocator myRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(p -> p
                        .path("/baidu")
                        .uri("http://www.baidu.com"))
                .build();
    }

    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        //表示允许跨域请求的方法
        config.addAllowedMethod("*");
        //表示允许所有的域都可以请求
        config.addAllowedOrigin("*");
        //表示允许跨域请求包含content-type
        config.addAllowedHeader("*");
        //暴露哪些头部信息（因为跨域访问默认不能获取全部头部信息）
        config.addExposedHeader(LoginTokenFilter.REFRESH_TOKEN);
        config.addExposedHeader("fileName");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }


}
